const request = require('../../utils/request')
const eventBus = require('../../utils/eventBus')

Page({
  data: {
    userPoints: 0,
    currentCategory: null,
    categories: [
      { id: 1, name: '课程优惠券', icon: '🎫' },
      { id: 2, name: '学习资料', icon: '📚' },
      { id: 3, name: '实物商品', icon: '🎁' }
    ],
    products: []
  },

  onLoad() {
    this.fetchUserPoints()
    this.fetchProducts()
  },

  async fetchProducts() {
    try {
      const { data } = await request({
        url: '/api/mall/products'
      })
      this.setData({ products: data })
    } catch (error) {
      console.error('获取商品列表失败:', error)
      wx.showToast({
        title: '获取商品列表失败',
        icon: 'none'
      })
    }
  },

  async fetchUserPoints() {
    try {
      // 获取当前用户ID
      const app = getApp();
      if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      const userId = app.globalData.userInfo.id;
      
      const { data } = await request({
        url: '/api/points/overview',
        data: { userId }
      })
      this.setData({
        userPoints: data.availablePoints
      })
    } catch (error) {
      console.error('获取用户积分失败:', error)
    }
  },

  switchCategory(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentCategory: this.data.currentCategory === index ? null : index
    })
  },

  exchangeProduct(e) {
    const { id, points, stock } = e.currentTarget.dataset
    
    if (stock <= 0 || points > this.data.userPoints) {
      wx.showToast({
        title: stock <= 0 ? '商品已售罄' : '积分不足',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '确认兑换',
      content: '确定要兑换该商品吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            // 获取当前用户ID
            const app = getApp();
            if (!app.globalData.isLoggedIn || !app.globalData.userInfo) {
              wx.showToast({
                title: '请先登录',
                icon: 'none'
              });
              return;
            }
            const userId = app.globalData.userInfo.id;
            
            await request({
              url: '/api/mall/exchange',
              method: 'POST',
              data: { 
                productId: id,
                userId
              }
            })

            // 更新本地数据
            this.setData({
              userPoints: this.data.userPoints - points
            })
            
            // 异步更新数据，不阻塞UI
            Promise.all([
              this.fetchProducts(),
              // 使用 wx.setStorageSync 存储更新标记，避免使用 EventBus
              wx.setStorageSync('pointsNeedUpdate', true)
            ]).catch(console.error)
            
            // 触发积分更新事件，使首页等页面实时更新积分
            eventBus.emit('pointsUpdate')

            wx.showToast({
              title: '兑换成功',
              icon: 'success'
            })
          } catch (error) {
            console.error('兑换失败:', error)
            wx.showToast({
              title: '兑换失败',
              icon: 'none'
            })
          }
        }
      }
    })
  },

  onUnload() {
    // 页面卸载时，不再使用 EventBus 触发事件
    // 改用本地存储标记，让目标页面在 onShow 时检查是否需要更新
  }
})